<template>
  <div class="system-config">
    <el-card>
      <div class="card-header">
        <span>系统配置管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加配置
          </el-button>
          <el-button @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </div>
      
      <el-form :inline="true" class="search-form" :model="searchForm" @submit.native.prevent>
        <el-form-item label="配置键">
          <el-input v-model="searchForm.configKey" placeholder="请输入配置键" clearable></el-input>
        </el-form-item>
        <el-form-item label="配置类型">
          <el-select v-model="searchForm.configType" placeholder="请选择配置类型" clearable>
            <el-option label="STRING" value="STRING"></el-option>
            <el-option label="NUMBER" value="NUMBER"></el-option>
            <el-option label="BOOLEAN" value="BOOLEAN"></el-option>
            <el-option label="JSON" value="JSON"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="configList" style="width: 100%" v-loading="loading">
        <el-table-column prop="configKey" label="配置键" min-width="200"></el-table-column>
        <el-table-column prop="configValue" label="配置值" min-width="300">
          <template slot-scope="scope">
            <!-- 编辑状态 -->
            <div v-if="editingId === scope.row.id" class="config-value-edit">
              <!-- 字符串类型 -->
              <!-- 横向布局的编辑区域 -->
              <div class="edit-content-wrapper">
                <!-- 输入控件区域 -->
                <div class="edit-input-wrapper">
                  <!-- 字符串类型 -->
                  <div v-if="scope.row.configType === 'STRING' || scope.row.configType === 'JSON'">
                    <el-input v-if="scope.row.configType === 'STRING'" 
                      v-model="tempValue" 
                      placeholder="请输入配置值" 
                      @keyup.enter.native="handleSave"
                      ref="editInput"></el-input>
                    <el-input v-else 
                      v-model="tempValue" 
                      type="textarea" 
                      placeholder="请输入JSON配置值" 
                      :rows="3" 
                      @keyup.enter.native.ctrl="handleSave"></el-input>
                  </div>
                  <!-- 数字类型 -->
                  <div v-else-if="scope.row.configType === 'NUMBER'">
                    <el-input-number v-model="tempValue" 
                      :min="-999999999" 
                      :max="999999999" 
                      placeholder="请输入数字" 
                      @change="handleSave"
                      ref="editNumber"></el-input-number>
                  </div>
                  <!-- 布尔类型 -->
                  <div v-else-if="scope.row.configType === 'BOOLEAN'">
                    <el-switch v-model="tempValue" 
                      active-color="#13ce66" 
                      inactive-color="#ff4949" 
                      @change="handleSave"></el-switch>
                  </div>
                </div>
                <!-- 操作按钮区域 -->
                <div class="edit-actions">
                  <el-button type="primary" size="small" icon="el-icon-check" @click="handleSave" class="action-btn save-btn"></el-button>
                  <el-button size="small" icon="el-icon-close" @click="handleCancelEdit" class="action-btn cancel-btn"></el-button>
                </div>
              </div>
            </div>
            <!-- 显示状态 -->
            <div v-else class="config-value-display" @click="handleStartEdit(scope.row)">
              <div class="description-tooltip">
                <el-tooltip effect="dark" content="点击编辑" placement="top">
                  <div>{{ scope.row.configValue || '无值' }}</div>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="configType" label="配置类型" width="120"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="200">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>{{ scope.row.description || '无描述' }}</p>
              <div slot="reference" class="description-tooltip">
                {{ scope.row.description || '无描述' }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="isEnabled" label="状态" width="100">
          <template slot-scope="scope">
            <el-switch 
              v-model="scope.row.isEnabled" 
              active-color="#13ce66" 
              inactive-color="#ff4949"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="160"></el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template slot-scope="scope">
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="el-dropdown-link">
                <i class="el-icon-setting"></i>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleEdit(scope.row)">修改</el-dropdown-item>
            <el-dropdown-item :command="{ type: 'delete', data: scope.row }" type="danger">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 添加配置行 -->
      <div v-if="showAddRow" class="add-config-row">
        <el-form :model="newConfig" ref="newConfigForm" :rules="addRules">
        <div class="add-config-row-inner">
          <div class="add-config-cell add-config-key">
            <el-form-item prop="configKey" style="margin-bottom: 0;">
              <el-input v-model="newConfig.configKey" placeholder="配置键" ref="addInput"></el-input>
            </el-form-item>
          </div>
          
          <div class="add-config-cell add-config-value">
            <el-form-item prop="configValue" style="margin-bottom: 0;">
              <!-- 根据配置类型显示不同的输入控件 -->
              <el-input v-if="newConfig.configType === 'STRING'" 
                v-model="newConfig.configValue" 
                placeholder="配置值"></el-input>
              <el-input-number v-else-if="newConfig.configType === 'NUMBER'"
                v-model="newConfig.configValue" 
                :min="-999999999" 
                :max="999999999" 
                placeholder="数字值"></el-input-number>
              <el-switch v-else-if="newConfig.configType === 'BOOLEAN'"
                v-model="newConfig.configValue" 
                active-color="#13ce66" 
                inactive-color="#ff4949"></el-switch>
              <el-input v-else-if="newConfig.configType === 'JSON'"
                v-model="newConfig.configValue" 
                type="textarea" 
                placeholder="JSON值" 
                :rows="2"></el-input>
            </el-form-item>
          </div>
          
          <div class="add-config-cell add-config-type">
            <el-form-item prop="configType" style="margin-bottom: 0;">
              <el-select v-model="newConfig.configType" placeholder="类型">
                <el-option label="STRING" value="STRING"></el-option>
                <el-option label="NUMBER" value="NUMBER"></el-option>
                <el-option label="BOOLEAN" value="BOOLEAN"></el-option>
                <el-option label="JSON" value="JSON"></el-option>
              </el-select>
            </el-form-item>
          </div>
          
          <div class="add-config-cell add-config-desc">
            <el-form-item prop="description" style="margin-bottom: 0;">
              <el-input v-model="newConfig.description" placeholder="描述"></el-input>
            </el-form-item>
          </div>
          
          <div class="add-config-cell add-config-status">
            <el-form-item style="margin-bottom: 0;">
              <el-switch v-model="newConfig.isEnabled" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
            </el-form-item>
          </div>
          
          <div class="add-config-cell add-config-create"></div>
          
          <div class="add-config-cell add-config-update"></div>
          
          <div class="add-config-cell add-config-actions">
            <div class="edit-actions">
              <el-button type="primary" size="small" @click="handleSaveNewConfig" class="action-btn save-btn">
                <i class="el-icon-check"></i>
              </el-button>
              <el-button size="small" @click="handleCancelAdd" class="action-btn cancel-btn">
                <i class="el-icon-close"></i>
              </el-button>
            </div>
          </div>
        </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'SystemConfigList',
  data() {
    return {
      configList: [],
      loading: false,
      searchForm: {
        configKey: '',
        configType: ''
      },
      // 编辑状态管理
      editingRow: null, // 当前正在编辑的行数据
      editingId: null,  // 当前正在编辑的ID
      tempValue: '',    // 临时存储编辑的值
      // 添加状态管理
      showAddRow: false, // 是否显示添加行
      newConfig: {
        configKey: '',
        configValue: '',
        configType: 'STRING',
        description: '',
        isEnabled: true
      }
    };
  },
  mounted() {
    console.log('SystemConfigList组件已挂载，准备加载配置数据');
    this.loadConfigs();
  },
  methods: {
    loadConfigs() {
      console.log('开始加载系统配置数据');
      this.loading = true;
      
      console.log('准备调用API:', this.$api.systemConfigApi);
      if (!this.$api || !this.$api.systemConfigApi) {
        console.error('API对象或systemConfigApi不存在');
        this.loading = false;
        return;
      }
      
      this.$api.systemConfigApi.getAll()
        .then(data => {
          console.log('获取系统配置数据成功:', data);
          // http.js已经处理了响应格式，这里直接获取数据
          let configData = data && data.data || [];
          console.log('过滤前的配置数据:', configData);
          // 应用搜索条件
          if (this.searchForm.configKey) {
            configData = configData.filter(item => item.configKey.includes(this.searchForm.configKey));
          }
          if (this.searchForm.configType) {
            configData = configData.filter(item => item.configType === this.searchForm.configType);
          }
          // 按创建时间正序排序
          configData.sort((a, b) => {
            return new Date(a.createTime) - new Date(b.createTime);
          });
          console.log('过滤并排序后的配置数据:', configData);
          this.configList = configData;
          this.loading = false;
        })
        .catch(error => {
          console.error('获取系统配置列表失败:', error);
          this.$message.error('获取系统配置列表失败');
          this.loading = false;
        });
    },
    
    handleSearch() {
      this.loadConfigs();
    },
    
    handleReset() {
      this.searchForm = {
        configKey: '',
        configType: ''
      };
      this.loadConfigs();
    },
    
    handleAdd() {
      // 显示添加行
      this.showAddRow = true;
      // 重置新配置数据
      this.newConfig = {
        configKey: '',
        configValue: '',
        configType: 'STRING',
        description: '',
        isEnabled: true
      };
      // 滚动到添加行
      this.$nextTick(() => {
        if (this.$refs.addInput) {
          this.$refs.addInput.focus();
        }
      });
    },
    
    handleEdit(row) {
      this.$router.push({
        path: '/system-config/edit',
        query: { id: row.id }
      });
    },
    
    handleDelete(row) {
      this.$confirm('确定要删除该系统配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.systemConfigApi.delete(row.id)
              .then(data => {
                this.$message.success('删除成功');
                this.loadConfigs();
              })
          .catch(error => {
            this.$message.error('删除失败: ' + error.message);
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    handleStatusChange(row) {
      // 更新状态
      this.$api.systemConfigApi.update(row.id, row)
        .then(data => {
          // 如果请求成功，不需要额外操作
          // http.js已经处理了响应
        })
        .catch(error => {
          // 如果请求失败，恢复原来的状态
          row.isEnabled = !row.isEnabled;
          this.$message.error('更新状态失败: ' + error.message);
        });
    },
    
    handleCommand(command) {
      if (command.type === 'edit') {
        this.handleEdit(command.data);
      } else if (command.type === 'delete') {
        this.handleDelete(command.data);
      }
    },
    
    // 开始编辑配置值
    handleStartEdit(row) {
      // 保存当前行数据用于取消时恢复
      this.editingRow = { ...row };
      this.editingId = row.id;
      
      // 根据配置类型处理临时值
      if (row.configType === 'BOOLEAN') {
        this.tempValue = row.configValue === 'true' || row.configValue === true;
      } else if (row.configType === 'NUMBER') {
        this.tempValue = Number(row.configValue);
      } else if (row.configType === 'JSON') {
        // 尝试格式化JSON，使其更易读
        try {
          this.tempValue = JSON.stringify(JSON.parse(row.configValue), null, 2);
        } catch (e) {
          this.tempValue = row.configValue;
        }
      } else {
        this.tempValue = row.configValue;
      }
      
      // 延迟聚焦输入框
      this.$nextTick(() => {
        if (this.$refs.editInput) {
          this.$refs.editInput.focus();
        } else if (this.$refs.editNumber) {
          this.$refs.editNumber.focus();
        }
      });
    },
    
    // 保存编辑后的配置值
    handleSave() {
      if (!this.editingRow || !this.editingId) return;
      
      // 创建要更新的数据
      const updatedData = {
        ...this.editingRow,
        configValue: this.tempValue
      };
      
      // 特殊处理JSON类型，确保是有效的JSON字符串
      if (updatedData.configType === 'JSON') {
        try {
          // 验证JSON格式是否有效
          JSON.parse(this.tempValue);
        } catch (e) {
          this.$message.error('JSON格式无效');
          return;
        }
      }
      
      // 调用API更新配置
      this.$api.systemConfigApi.update(updatedData.id, updatedData)
        .then(() => {
          this.$message.success('配置更新成功');
          // 更新本地数据
          const index = this.configList.findIndex(item => item.id === updatedData.id);
          if (index !== -1) {
            this.configList.splice(index, 1, updatedData);
          }
          this.handleCancelEdit();
        })
        .catch(error => {
          this.$message.error('配置更新失败: ' + error.message);
        });
    },
    
    // 取消编辑
    handleCancelEdit() {
      this.editingId = null;
      this.editingRow = null;
      this.tempValue = '';
    },
    
    handleRefresh() {
      this.loadConfigs();
    },
    
    // 保存新配置
    handleSaveNewConfig() {
      this.$refs.newConfigForm.validate((valid) => {
        if (valid) {
          // 特殊处理JSON类型，确保是有效的JSON字符串
          if (this.newConfig.configType === 'JSON') {
            try {
              // 验证JSON格式是否有效
              JSON.parse(this.newConfig.configValue);
            } catch (e) {
              this.$message.error('JSON格式无效');
              return;
            }
          }
          
          // 提交新配置
          this.$api.systemConfigApi.add(this.newConfig)
            .then(() => {
              this.$message.success('配置添加成功');
              this.showAddRow = false;
              this.loadConfigs(); // 重新加载配置列表
            })
            .catch(error => {
              this.$message.error('配置添加失败: ' + error.message);
            });
        }
      });
    },
    
    // 取消添加新配置
    handleCancelAdd() {
      this.showAddRow = false;
    }
  },
  
  computed: {
    // 添加配置表单的验证规则
    addRules() {
      return {
        configKey: [
          { required: true, message: '请输入配置键', trigger: 'blur' },
          { max: 100, message: '配置键不能超过100个字符', trigger: 'blur' }
        ],
        configType: [
          { required: true, message: '请选择配置类型', trigger: 'change' }
        ],
        configValue: [
          { required: true, message: '请输入配置值', trigger: 'blur' },
          { max: 2000, message: '配置值不能超过2000个字符', trigger: 'blur' }
        ],
        description: [
          { max: 500, message: '描述信息不能超过500个字符', trigger: 'blur' }
        ]
      };
    }
  }
};
</script>

<style scoped>
.system-config {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
}

.search-form {
  margin-bottom: 20px;
}

.description-tooltip {
  cursor: pointer;
  color: #409EFF;
}

/* 配置值编辑区域样式 */
.config-value-edit {
  width: 100%;
  padding: 4px 0;
}

/* 配置值显示区域样式 */
.config-value-display {
  cursor: pointer;
}

/* 横向布局的编辑内容包装器 */
.edit-content-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  width: 100%;
}

/* 输入控件区域 */
.edit-input-wrapper {
  flex: 1;
  min-width: 0;
}

/* 输入控件样式 */
.edit-input-wrapper .el-input,
.edit-input-wrapper .el-input-number {
  width: 100%;
}

/* 编辑操作按钮样式 */
.edit-actions {
  display: flex;
  flex-direction: row;
  gap: 4px;
  min-width: 60px;
}

/* 绿色方块按钮样式 */
.action-btn {
  width: 32px;
  height: 32px;
  border-radius: 0;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 保存按钮样式 */
.save-btn {
  background-color: #13ce66;
  border-color: #13ce66;
  color: white;
}

.save-btn:hover {
  background-color: #10b859;
  border-color: #10b859;
}

/* 取消按钮样式 */
.cancel-btn {
  background-color: #f0f0f0;
  border-color: #dcdfe6;
  color: #606266;
}

.cancel-btn:hover {
  background-color: #e6e6e6;
  border-color: #c0c4cc;
}

/* 添加配置行样式 */
.add-config-row {
  margin-top: 20px;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  background-color: #fafafa;
  /* 添加内边距以匹配表格内容区域 */
  padding-left: 16px;
  padding-right: 16px;
}

/* 添加配置行内部布局 */
.add-config-row-inner {
  display: flex;
  align-items: center;
  width: 100%;
}

/* 添加配置行单元格样式 */
.add-config-cell {
  display: flex;
  align-items: center;
  /* 确保单元格内容垂直居中 */
  height: 40px;
}

/* 各个单元格宽度设置，与表格列精确对齐 */
.add-config-key {
  width: 200px; /* 与表格配置键列(min-width: 200px)精确对齐 */
}

.add-config-value {
  width: 300px; /* 与表格配置值列(min-width: 300px)精确对齐 */
  margin-left: 20px;
}

.add-config-type {
  width: 120px; /* 与表格配置类型列(width: 120px)精确对齐 */
  margin-left: 20px;
  /* 确保select组件完全填充单元格 */
}

/* 确保配置类型的select组件宽度正确 */
.add-config-cell.add-config-type .el-form-item {
  width: 120px;
}

/* 调整配置类型的select组件样式 */
.add-config-cell.add-config-type .el-select {
  width: 120px;
}

.add-config-desc {
  width: 200px; /* 与表格描述列(min-width: 200px)精确对齐 */
  margin-left: 20px;
}

.add-config-status {
  width: 100px; /* 与表格状态列(width: 100px)精确对齐 */
  margin-left: 20px;
  justify-content: center;
}

.add-config-create {
  width: 160px; /* 与表格创建时间列(min-width: 160px)精确对齐 */
  margin-left: 20px;
}

.add-config-update {
  width: 160px; /* 与表格更新时间列(min-width: 160px)精确对齐 */
  margin-left: 20px;
}

.add-config-actions {
  width: 80px; /* 与表格操作列(width: 80px)精确对齐 */
  margin-left: auto; /* 自动计算右侧间距，确保与固定列对齐 */
  justify-content: center;
}

/* 确保输入控件宽度适应单元格 */
.add-config-cell .el-input,
.add-config-cell .el-input-number,
.add-config-cell .el-select {
  width: 100%;
}

/* 调整switch控件对齐 */
.add-config-status .el-switch {
  margin: 0;
}

/* 操作按钮区域样式 */
.add-config-actions .edit-actions {
  display: flex;
  justify-content: center;
}

/* 确保表单项目没有额外的边距影响对齐 */
.add-config-row .el-form-item {
  margin-bottom: 0;
  display: flex;
  width: 100%;
}
</style>